﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Main
{
    public partial class ProductsCatalog : System.Web.UI.Page
    {
        ControlProducts.Control prod = new ControlProducts.Control();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["ID"] != null)
            {

            }
            else
                Response.Redirect("Login.aspx");
        }

        /// <summary>
        /// searches throughout existing products for matching criteria
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                lblError.Text = String.Empty;

                if (txtSearch.Text.Length > 0)
                {
                    listResult.Items.Clear();
                    if (!ListMatchingProducts(prod.ViewProduct(Session["Company"].ToString()), txtSearch.Text))
                    {
                        lblSearchError.Visible = true;
                        lblSearchError.Text = "No product found!";
                        tblResult.Visible = false;
                    }
                }
                else
                {
                    listResult.Items.Clear();
                    if (!ListAllProducts(prod.ViewProduct(Session["Company"].ToString())))
                    {
                        lblSearchError.Visible = true;
                        lblSearchError.Text = "No product found!";
                        tblResult.Visible = false;
                    }
                }
            }
            catch (Exception ex)
            {
                lblSearchError.Visible = true;
                lblSearchError.Text = ex.ToString();
            }
        }

        /// <summary>
        /// returns product info if criteria matched
        /// </summary>
        /// <param name="list"></param>
        /// <param name="searchValue"></param>
        /// <returns></returns>
        private Boolean ListMatchingProducts(List<Product> list, string searchValue)
        {
            TechnoStoreMainDataContext db = new TechnoStoreMainDataContext();
            var prodQuery = from u in db.Products
                            where u.name.Contains(searchValue) == true || u.type.Contains(searchValue) == true
                            select u.ID;
            int[] matchedProdID = prodQuery.ToArray();

            if (list.Count == 0)
                return false;
            else if (matchedProdID.Length == 0)
                return false;
            else
            {
                foreach (var productList in list)
                {
                    foreach (var productID in matchedProdID)
                    {
                        if (productList.ID == productID)
                        {
                            ListItem prodItem = new ListItem();
                            prodItem.Text = productList.type + ": " + productList.name + " - $" + productList.price;
                            listResult.Items.Add(prodItem);
                        }
                        else if (productList.ID != productID && listResult.Items.Count < 0)
                            return false;
                    }
                }
                tblResult.Visible = true;
                lblSearchError.Visible = false;
                db.Dispose();
                return true;
            }
        }

        /// <summary>
        /// returns product info for all existing products
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        private Boolean ListAllProducts(List<Product> list)
        {
            foreach (var Result in list)
            {
                if (list.Count == 0)
                {
                    return false;
                }
                else
                {
                    ListItem prodItem = new ListItem();
                    prodItem.Text = Result.type + ": " + Result.name + " - $" + Result.price;
                    listResult.Items.Add(prodItem);
                }
            }
            tblResult.Visible = true;
            lblSearchError.Visible = false;
            return true;
        }

        /// <summary>
        /// triggers creation of a new product on SQL Azure
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnCreate_Click(object sender, EventArgs e)
        {
            try
            {
                ControlCommon common = new ControlCommon();
                String msg = prod.CreateNewProduct(common.ConvertToEnglish(txtName.Text), common.ConvertToEnglish(txtType.Text), Convert.ToInt32(txtPrice.Text), Session["Company"].ToString());

                if (msg == String.Empty)
                {
                    lblError.Text = "New product has been successfully created!";
                    listResult.Items.Clear();
                    ListAllProducts(prod.ViewProduct(Session["Company"].ToString()));
                }
                else
                    lblError.Text = msg;
            }
            catch (Exception ex)
            {
                lblError.Text = ex.ToString();
            }
        }

        /// <summary>
        /// makes all fields blank
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnReset_Click(object sender, EventArgs e)
        {
            txtName.Text = String.Empty;
            txtType.Text = String.Empty;
            txtPrice.Text = String.Empty;
            lblError.Text = String.Empty;
        }
    }
}